import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mall/core/models/coin_type.dart';
import 'package:mall/core/models/order_checkout.dart';
import 'package:mall/core/models/order_checkout_req.dart';
import 'package:mall/core/models/order_confirm.dart';
import 'package:mall/core/models/product_detail.dart';
import 'package:mall/core/services/api.dart';
import 'package:provider/provider.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:tobias/tobias.dart' as tobias;

/// 订单支付
class OrderPaySheet extends StatefulWidget {
  final List<int> portIds;
  final OrderConfirm orderConfirm;
  final int addressId;
  final Map<int, int> storeCarts;
  final Map<int, String> orderMemos;

  const OrderPaySheet({
    Key key,
    @required this.portIds,
    @required this.orderConfirm,
    @required this.addressId,
    @required this.storeCarts,
    @required this.orderMemos,
  }) : super(key: key);

  @override
  _OrderPaySheetState createState() => _OrderPaySheetState();
}

class _OrderPaySheetState extends State<OrderPaySheet> {
  // 选择的支付方式
  MapEntry<String, String> _payMode;

  // 积分密码
  TextEditingController _passwordController;
  GlobalKey<FormState> _formKey = GlobalKey();
  Map<String, String> _coinPayPasswords = {};

  @override
  void initState() {
    super.initState();
    // 默认支付方式
    _payMode = widget.orderConfirm.payModes.entries.firstWhere(
      (element) => element.key == 'WX_PAY' || element.key == 'ALI_PAY',
      orElse: () => null,
    );
    _passwordController = TextEditingController();
  }

  @override
  void dispose() {
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var pricePointMap = _pricePointMap();
    return SafeArea(
      child: SingleChildScrollView(
        padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
        child: Column(
          children: [
            // 标题
            Container(
              alignment: Alignment.center,
              color: Color(0xFFFC3B3B),
              height: 44.w,
              child: Text(
                "确认支付",
                style: TextStyle(color: Colors.white, fontSize: 14.sp),
              ),
            ),
            Container(
              padding: EdgeInsets.all(20.w),
              color: Color(0xFFF3F1F1),
              width: double.infinity,
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    // 现金
                    _buildRmb(),
                    Divider(color: Color(0xFFBBBBBB), height: 40.w, thickness: 1.w),
                    // 积分分组
                    ...List.generate(
                      pricePointMap.length,
                      (index) => _buildPointItem(pricePointMap.values.toList()[index]),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        OutlineButton(
                          onPressed: () => Navigator.of(context).pop(),
                          borderSide: BorderSide(color: Theme.of(context).primaryColor),
                          child: Text('放弃支付'),
                        ),
                        RaisedButton(
                          onPressed: _onTapConfirm,
                          elevation: 0,
                          child: Text('确认支付'),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 人民币支付
  Widget _buildRmb() {
    final priceRmbs = _priceRmbs();
    if (priceRmbs.isEmpty) {
      return Container();
    }
    var totalPrice = 0.0;
    priceRmbs.forEach((element) => totalPrice += element.pointCoin);
    return Column(
      children: [
        Text.rich(
          TextSpan(
            text: "¥",
            style: TextStyle(fontSize: 12.sp),
            children: [
              TextSpan(
                text: '$totalPrice',
                style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 18.sp),
              )
            ],
          ),
        ),
        SizedBox(height: 20.w),
        Wrap(
          runSpacing: 2.w,
          children: List.generate(
            widget.orderConfirm.payModes.length,
            (index) => _buildPayMode(widget.orderConfirm.payModes.entries.toList()[index]),
          ),
        ),
      ],
    );
  }

  List<Price> _priceRmbs() {
    return widget.orderConfirm.totalPriceVos
        .where((element) => element.coinType == CoinType.RMB && element.pointCoin > 0)
        .toList();
  }

  Widget _buildPayMode(MapEntry<String, String> payMode) {
    if (payMode.key != 'WX_PAY' && payMode.key != 'ALI_PAY') {
      return Container();
    }
    return GestureDetector(
      onTap: () => _onTapPayMode(payMode),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 4.w, horizontal: 8.w),
        color: Colors.white,
        child: Row(
          children: [
            if (payMode.key == 'WX_PAY') Image.asset('assets/image/wxpay.png', height: 20.w),
            if (payMode.key == 'ALI_PAY') Image.asset('assets/image/alipay.png', height: 20.w),
            Spacer(),
            Icon(
              Icons.check_circle,
              size: 16.w,
              color: _payMode.key == payMode.key ? Theme.of(context).primaryColor : Colors.grey,
            ),
          ],
        ),
      ),
    );
  }

  void _onTapPayMode(MapEntry<String, String> payMode) {
    setState(() {
      _payMode = payMode;
    });
  }

  /// 积分支付
  Widget _buildPointItem(List<Price> pricePoints) {
    if (pricePoints.isEmpty) {
      return Container();
    }
    var totalPrice = 0.0;
    pricePoints.forEach((element) => totalPrice += element.pointCoin);
    final price = pricePoints.first;
    return Column(
      children: [
        Text.rich(
          TextSpan(
            text: '${price.flag}',
            style: TextStyle(fontSize: 12.sp),
            children: [
              TextSpan(
                text: '$totalPrice',
                style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 18.sp),
              )
            ],
          ),
        ),
        SizedBox(height: 20.w),
        TextFormField(
          enabled: price.needPassword,
          decoration: InputDecoration(
            hintText: price.needPassword ? '请输入${price.priceTypeName}保护密码' : '免密',
          ),
          keyboardType: TextInputType.visiblePassword,
          obscureText: true,
          onSaved: (value) => _coinPayPasswords[price.accountType] = value,
        ),
        SizedBox(height: 20.w),
      ],
    );
  }

  /// 将所有积分类型按账户AccountType分组
  Map<String, List<Price>> _pricePointMap() {
    final Map<String, List<Price>> map = {};
    for (var item in widget.orderConfirm.totalPriceVos) {
      debugPrint("item: ${item.toJson()}");
      // 排除人民币和免费
      if (item.coinType == CoinType.RMB || item.pointCoin <= 0) {
        continue;
      }
      var list = map[item.accountType];
      if (list == null) {
        map[item.accountType] = [item];
      } else {
        list.add(item);
      }
    }
    return map;
  }

  /// 点击确认支付
  void _onTapConfirm() async {
    // 支付类型
    if (_priceRmbs() != null && _payMode == null) {
      EasyLoading.showToast('请选择支付方式');
      return;
    }
    // 积分密码
    _formKey.currentState.save();
    final pricePointMap = _pricePointMap();
    for (var item in pricePointMap.entries) {
      var price = item.value.first;
      if (price.needPassword && _coinPayPasswords[price.accountType].isEmpty) {
        EasyLoading.showToast('请输入${price.priceTypeName}密码');
        return;
      }
    }
    // 支付
    final api = context.read<Api>();
    EasyLoading.show();
    try {
      final req = OrderCheckoutReq(
        addressId: widget.addressId,
        storeCarts: widget.storeCarts,
        payType: _payMode?.key,
        coinPayPasswords: _coinPayPasswords,
        userPortMappingIds: widget.portIds,
        orderMemos: widget.orderMemos,
      );
      final orderCheckout = await api.orderCheckoutNew(req);
      EasyLoading.dismiss();
      //  如果需要支付就去支付
      if (orderCheckout.pay) {
        if (orderCheckout.payMode == PayMode.WX_PAY) {
          // 微信支付
          final result = orderCheckout.sign;
          fluwx.payWithWeChat(
            appId: result['appid'].toString(),
            partnerId: result['partnerid'].toString(),
            prepayId: result['prepayid'].toString(),
            packageValue: result['package'].toString(),
            nonceStr: result['noncestr'].toString(),
            timeStamp: result['timestamp'],
            sign: result['sign'].toString(),
          );
          final response = await fluwx.weChatResponseEventHandler
              .firstWhere((element) => element is fluwx.WeChatPaymentResponse)
              .timeout(Duration(minutes: 1));
          if (!response.isSuccessful) {
            throw response.errStr ?? '支付失败';
          }
        } else if (orderCheckout.payMode == PayMode.ALI_PAY) {
          // 支付宝支付
          Map<dynamic, dynamic> result = await tobias.aliPay(orderCheckout.sign);
          debugPrint('支付宝支付结果：$result');
          if (result['resultStatus']?.toString() != '9000') {
            throw result['memo']?.toString() ?? '支付失败';
          }
        }
      }
      EasyLoading.showToast('支付成功');
      // 返回需要跳转的页面
      Navigator.of(context).pop(orderCheckout);
    } on DioError catch (e) {
      EasyLoading.showToast('${e.message}');
    } catch (e) {
      EasyLoading.showToast('$e');
    }
  }
}
